package com.xbongbong.pro.statistic.help;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.paas.domain.entity.PaasFormSubDataEntity;
import com.xbongbong.paas.elasticsearch.pojo.ChartFieldsAnalysisEntityExt;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.pojo.dto.PaasFormDataEsMappingDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.helper.PageHelper;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.pro.domain.entity.ChartEntity;
import com.xbongbong.pro.statistic.pojo.SlaveSourcePojo;
import com.xbongbong.saas.model.IndexTypeModel;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 单表处理
 * @author zhouwq
 * @date 2020/10/20 14:33
 */
@Component
public class BiSubFormDataSingleHandle extends AbstractBiSubFormDataHelp{
    
    @Resource
    private IndexTypeModel indexTypeModel;

    @Override
    public void handleSubFormData(List esList, ChartEntity chartEntity, PageHelper pageHelper, JSONArray tableHead, BoolQueryBuilder boolQueryBuilder, SearchRequest searchRequest) throws XbbException, IllegalAccessException {
        JSONObject driverSourcesObject = chartEntity.getDriverSources();
        SlaveSourcePojo driverSourcePojo = JSON.toJavaObject(driverSourcesObject, SlaveSourcePojo.class);
        //单表
        PaasFormDataEsMappingDTO paasFormDataEsMappingDTO = new PaasFormDataEsMappingDTO();
        BeanUtil.copyProperties(driverSourcePojo, paasFormDataEsMappingDTO);
        IndexTypeEnum indexTypeEnum = indexTypeModel.getIndexType(chartEntity.getCorpid(), driverSourcePojo.getBusinessType(), driverSourcePojo.getSaasMark());
        String type = indexTypeEnum.getType();
        SearchRequest searchSubFormRequest = new SearchRequest(searchRequest.indices());
        PageRequest pageSubFormRequest = subFormSearchQueryBuild(type, chartEntity.getCorpid(), pageHelper, boolQueryBuilder, searchSubFormRequest);
        XbbAggregatedPage<PaasFormSubDataEntity> formSubDataList = xbbElasticsearchRestTemplate.queryForPages(pageSubFormRequest, searchSubFormRequest, PaasFormSubDataEntity.class);
        Map<String, List<String>> subFormAttrList = subFormAttrListGet(tableHead);
        //parentID 父esId -> （attr 字段名 -> 对应字段的子表单集合）
        Map<Long, Map<String, JSONArray>> parentIdToList = new HashMap<>(1 << 4);
        for (PaasFormSubDataEntity entity : formSubDataList.getContent()) {
            Long parentId = entity.getDataId();
            Map<String, JSONArray> attrToList = new HashMap<>(1 << 4);
            JSONArray entities = new JSONArray();
            entities.add(entity.getData());
            attrToList.put(entity.getAttr(), entities);
            parentIdToList.merge(parentId, attrToList, (oldest, latest) -> {
                JSONArray list = new JSONArray();
                list.add(entity.getData());
                oldest.merge(entity.getAttr(), list, (v1, v2) -> {
                    v1.addAll(v2);
                    return v1;
                });
                return oldest;
            });
        }
        for (Object obj : esList) {
            ChartFieldsAnalysisEntityExt e = (ChartFieldsAnalysisEntityExt) obj;
            Long id = e.getDataId();
            Map<String, JSONArray> attrToList = parentIdToList.get(id);
            if (attrToList == null) {
                continue;
            }
            JSONObject data = e.getData();
            if (data == null) {
                data = new JSONObject();
            }
            for (Map.Entry<String, List<String>> entry : subFormAttrList.entrySet()) {
                String key = entry.getKey();
                JSONArray list = attrToList.get(key);
                if (list == null || list.size() == 0) {
                    continue;
                }
                data.put(key, list);
            }
            e.setData(data);
        }

    }
    
}
